package com.example.healthcode2.Other;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;

import android.os.IBinder;


import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.healthcode2.R;
import com.example.healthcode2.indexActivity;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class GpsService extends Service {
    private LocationManager lm;
    public static Location location2;
    //通知
    private static final String CHANNEL_ID2 = "Channel2";
    public int notifId_1 = 0x1;
    private String name = null;

    public GpsService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notifaction();//启动前台通知
        }

    }

    //通知
    private void notifaction() {
        createNotificationChannel();//创建通道
        NotificationCompat.Builder repliedNotification = new NotificationCompat.Builder(this, CHANNEL_ID2);
        repliedNotification.setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentText("这是一个前台通知").setContentTitle("是为了服务一直运行");

        Notification notification = repliedNotification.build();
        startForeground(notifId_1, notification);


    }

    //通知通道注册
    private void createNotificationChannel() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID2, "退出界面显示的通知", importance);
            channel.setImportance(NotificationManager.IMPORTANCE_HIGH);//重要性
            channel.enableLights(false);
            channel.setSound(null, null);
            channel.enableVibration(false);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }


    }

    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        flags = START_STICKY;//手动返回START_STICKY，当service因内存不足被kill，当内存又有的时候，service又被重新创建，比较不错，但是不能保证任何情况下都被重建，比如进程被干掉了….
        System.out.println("服务启动");
        name = (String) intent.getSerializableExtra("name");//获取参数
        if (name == null) {//若为空
            try {
                name = readfile("name.txt");//从存储中获取
            } catch (IOException e) {
                stopService(intent);
                e.printStackTrace();
            }
        }
        if (name.isEmpty()) {//name为空停止服务
            onDestroy();
        }
        if (initGPS(flags))//初始化GPS
        {
            return super.onStartCommand(intent, flags, startId);
        }
        uploaddata();//上传用户数据
        return super.onStartCommand(intent, flags, startId);
    }

    //读取文件
    private String readfile(String filename) throws IOException {
        InputStream in = openFileInput(filename);
        byte[] bytes = new byte[1024];
        StringBuffer sb = new StringBuffer();
        int len = -1;
        while ((len = in.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }
        in.close();
        return sb.toString();
    }

    //定时上传数据
    private void uploaddata() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    try {
                        if (location2 != null) {

                            System.out.println("name：" + name + " 纬度:" + location2.getLatitude() + " 经度" + location2.getLongitude() + "  时间:" + location2.getTime());
                            HttpGpsRequest();//发送用户位置

                        }
                        Thread.sleep(600000);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    //发送位置给服务器
    private void HttpGpsRequest() {
        final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        String url = "http://30r97104b2.qicp.vip/user/location";
        final StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                    }
                }) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
//                if (name==null){
//                    try {
//                        name = readfile("name.txt");//从存储中获取
//                        if (name.isEmpty()){
//                            onDestroy();
//                        }
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                        onDestroy();
//                    }
//                }
//                if (name.isEmpty()){
//                    try {
//                        name = readfile("name.txt");//从存储中获取
//                        if (name.isEmpty()){
//                            onDestroy();
//                        }
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                        onDestroy();
//                    }
//                }

                params.put("username", name);
                params.put("longitude", location2.getLongitude() + "");
                params.put("latitude", location2.getLatitude() + "");
                return params;
            }
        };

        queue.add(request);//发送请求

    }

    //GPS开启程序
    private boolean initGPS(int flags) {
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return true;
        }

//        Location lc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//        updateShow(lc);
        location2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        //设置间隔30秒获得一次GPS定位信息.
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 8, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // 当GPS定位信息发生改变时，更新定位
                System.out.println("定位信息更新了");
                updateShow(location);
                location2 = location;
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {
                // 当GPS LocationProvider可用时，更新定位
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                    return;
                }
                updateShow(lm.getLastKnownLocation(provider));
                location2 = lm.getLastKnownLocation(provider);
            }

            @Override
            public void onProviderDisabled(String provider) {
                updateShow(null);
            }
        });
        return false;
    }


    private void updateShow(Location location) {
        if (location != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("当前的位置信息：\n");
            sb.append("精度：" + location.getLongitude() + "\n");
            sb.append("纬度：" + location.getLatitude() + "\n");

            System.out.println(sb);
        } else {
            System.out.println("no location");
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("GpsService服务被Kill了");
//        Intent intent=new Intent(getBaseContext(),GpsReceiver.class);
//        intent.setAction("com.example.startgps.destroy");
//        sendBroadcast(intent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopForeground(true);
        }
    }
}
